package com.tomehay.termprojectmanage_server.service.impl;


import com.alibaba.druid.util.StringUtils;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.tomehay.termprojectmanage_server.enums.ResponseCode;
import com.tomehay.termprojectmanage_server.mapper.*;
import com.tomehay.termprojectmanage_server.pojo.Model.*;
import com.tomehay.termprojectmanage_server.pojo.VO.GroupTaskVO;
import com.tomehay.termprojectmanage_server.pojo.VO.ResultVO;
import com.tomehay.termprojectmanage_server.service.GroupTaskService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.time.LocalDateTime;
import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author tomehay
 * @since 2023-06-20
 */
@Service
public class GroupTaskServiceImpl extends ServiceImpl<GroupTaskMapper, GroupTask> implements GroupTaskService {

    @Value("${filePath}")
    private String filePath;

    @Resource
    GroupTaskMapper groupTaskMapper;

    @Resource
    GroupMemberMapper groupMemberMapper;

    @Resource
    StudentMapper studentMapper;

    @Resource
    TermprojectMapper termprojectMapper;

    @Resource
    CourseMapper courseMapper;

    @Resource
    TermMapper termMapper;

    @Override
    public List<GroupTask> queryPage(Integer groupID,Integer termProjectId) {
        return baseMapper.selectInfoById(groupID,termProjectId);
    }

    @Override
    public ResultVO<List<GroupTaskVO>> FindUnEndedGroupTask(int courseId) {
        List<GroupTaskVO> groupTasks = groupTaskMapper.selectGroupTaskVO(courseId,0);

        for (GroupTaskVO groupTaskVO: groupTasks) {
            groupTaskVO.setGroupMemberNames(
                    GroupMember.GetMembers(groupMemberMapper
                    ,groupTaskVO.getGroupId()
                    ,studentMapper)
            );
            groupTaskVO.setTaskStatus(GroupTask.mMap.get(groupTaskVO.getStatus()));
        }

        return new ResultVO<>(ResponseCode.auto(groupTasks),groupTasks);
    }

    @Override
    public ResultVO<List<GroupTaskVO>> FindEndedGroupTask(int courseId) {
        List<GroupTaskVO> groupTasks = groupTaskMapper.selectGroupTaskVO(courseId,1);

        for (GroupTaskVO groupTaskVO: groupTasks) {
            groupTaskVO.setGroupMemberNames(
                    GroupMember.GetMembers(groupMemberMapper,
                    groupTaskVO.getGroupId(),
                    studentMapper)
            );

            groupTaskVO.setTaskStatus(GroupTask.mMap.get(groupTaskVO.getStatus()));
        }

        return new ResultVO<>(ResponseCode.auto(groupTasks),groupTasks);
    }

    @Override
    public ResultVO<Void> CreateTask(GroupTask groupTask) {
        groupTask.setCreateTime(LocalDateTime.now());
        groupTask.setGroupTaskNo("143"+System.currentTimeMillis());
        groupTask.setIsEnd(0);
        groupTask.setStatus(0);
        groupTaskMapper.insert(groupTask);
        return new ResultVO<>(ResponseCode.OK);
    }

    @Override
    public ResultVO<Void> EndGroupTask(int id) {
        GroupTask groupTask = groupTaskMapper.selectById(id);
        groupTask.setIsEnd(1);
        groupTaskMapper.updateById(groupTask);
        return new ResultVO<>(ResponseCode.OK);
    }

    @Override
    public ResultVO<GroupTask> GetOne(int id) {
        GroupTask groupTask = groupTaskMapper.selectById(id);
        return new ResultVO<>(ResponseCode.auto(groupTask),groupTask);
    }

    @Override
    public ResultVO<Void> RejectTask(int id) {
        GroupTask groupTask = groupTaskMapper.selectById(id);
        groupTask.setIsEnd(0);
        groupTask.setStatus(4);
        groupTaskMapper.updateById(groupTask);
        return new ResultVO<>(ResponseCode.OK);
    }

    @Override
    public ResultVO<List<GroupTaskVO>> FindUnEndedGroupTaskByTermProjectId(int termProjectId) {
        List<GroupTaskVO> groupTasks = groupTaskMapper.selectGroupTaskVOByTermProjectID(0,termProjectId);

        for (GroupTaskVO groupTaskVO: groupTasks) {
            groupTaskVO.setGroupMemberNames(
                    GroupMember.GetMembers(groupMemberMapper
                            ,groupTaskVO.getGroupId()
                            ,studentMapper)
            );
            groupTaskVO.setTaskStatus(GroupTask.mMap.get(groupTaskVO.getStatus()));
        }

        return new ResultVO<>(ResponseCode.auto(groupTasks),groupTasks);
    }

    @Override
    public ResultVO<List<GroupTaskVO>> FindEndedGroupTaskByTermProjectId(int termProjectId) {
        List<GroupTaskVO> groupTasks = groupTaskMapper.selectGroupTaskVOByTermProjectID(1,termProjectId);

        for (GroupTaskVO groupTaskVO: groupTasks) {
            groupTaskVO.setGroupMemberNames(
                    GroupMember.GetMembers(groupMemberMapper
                            ,groupTaskVO.getGroupId()
                            ,studentMapper)
            );
            groupTaskVO.setTaskStatus(GroupTask.mMap.get(groupTaskVO.getStatus()));
        }

        return new ResultVO<>(ResponseCode.auto(groupTasks),groupTasks);
    }

    @Override
    public ResultVO<Void> UpLoadCode(MultipartFile multipartFile, int id) throws IOException {
        GroupTask groupTask = groupTaskMapper.selectById(id);
//        groupTask.setStatus(1);

        Termproject termproject = termprojectMapper.getTermProjectByAllocation(groupTask.getAllocationId());
        Course course = courseMapper.selectById(termproject.getCourseId());
        String TermName = termMapper.getTermName(course.getTermId());

        String path = filePath+TermName+"\\"+course.getCourseName()+"\\"+termproject.getTitle()+"\\代码\\"+multipartFile.getOriginalFilename();
        System.out.println(path);

        File file = new File(path);
        createFile(file);
        multipartFile.transferTo(file);

        groupTask.setCode(path);
        groupTaskMapper.updateById(groupTask);

        return new ResultVO<>(ResponseCode.OK);
    }

    @Override
    public ResultVO<Void> UpLoadDoc(MultipartFile multipartFile, int id) throws IOException {
        GroupTask groupTask = groupTaskMapper.selectById(id);
//        groupTask.setStatus(1);

        Termproject termproject = termprojectMapper.getTermProjectByAllocation(groupTask.getAllocationId());
        Course course = courseMapper.selectById(termproject.getCourseId());
        String TermName = termMapper.getTermName(course.getTermId());

        String path = filePath+TermName+"\\"+course.getCourseName()+"\\"+termproject.getTitle()+"\\文档\\"+multipartFile.getOriginalFilename();
        System.out.println(path);

        File file = new File(path);
        createFile(file);
        multipartFile.transferTo(file);

        groupTask.setDocument(path);
        groupTaskMapper.updateById(groupTask);

        return new ResultVO<>(ResponseCode.OK);
    }

    @Override
    public void exportFile(String path, HttpServletResponse response) throws IOException {
        //创建文件对象，传递路径参数
        File file = new File(path);
        //获取文件
        String filename1 = file.getName();
        //创建缓冲流
        InputStream fis = new BufferedInputStream(new FileInputStream(path));
        byte[] buffer = new byte[fis.available()];
        //读操作
        fis.read(buffer);
        //关流
        fis.close();
        //设置响应信息 (响应编码等)
        response.reset();
        response.setHeader("Content-Disposition", "attachment;filename=" + new String(filename1.getBytes(), "iso-8859-1"));
        response.setContentType("application/vnd.ms-excel;charset=UTF-8");
        response.setHeader("Pragma", "no-cache");
        response.setHeader("Cache-Control", "no-cache");
        response.setDateHeader("Expires", 0);
        //响应输出流
        OutputStream toClient = new BufferedOutputStream(response.getOutputStream());
        //写操作
        toClient.write(buffer);
        //刷新
        toClient.flush();
        //关流
        toClient.close();
    }

    @Override
    public ResultVO<Void> FinishGroupTask(int id) {
        UpdateWrapper updateWrapper = new UpdateWrapper<>();
        updateWrapper.set("status",1);
        updateWrapper.eq("id",id);

        groupTaskMapper.update(null,updateWrapper);
        return new ResultVO<>(ResponseCode.OK);
    }

    @Override
    public ResultVO<Void> DeleteCode(int id, String path) {
        GroupTask groupTask = groupTaskMapper.selectById(id);
        groupTask.setCode(null);

        LambdaUpdateWrapper<GroupTask> lambdaUpdate = Wrappers.lambdaUpdate();
        //构建where条件根据id修改
        lambdaUpdate.eq(GroupTask::getId, groupTask.getId());
        //name属性为空时可以修改字段为NULL
        if (StringUtils.isEmpty(groupTask.getCode())) lambdaUpdate.set(GroupTask::getCode, null);
        //此时生成的SQL语句为update order set price = 3.8, name = null where id = 1
        super.update(groupTask, lambdaUpdate);


        File file = new File(path);
        if (file.exists()) {
            file.delete();
        }

        return new ResultVO<>(ResponseCode.OK);
    }

    @Override
    public ResultVO<Void> DeleteDoc(int id, String path) {
        GroupTask groupTask = groupTaskMapper.selectById(id);
        groupTask.setDocument(null);

        LambdaUpdateWrapper<GroupTask> lambdaUpdate = Wrappers.lambdaUpdate();
        //构建where条件根据id修改
        lambdaUpdate.eq(GroupTask::getId, groupTask.getId());
        //name属性为空时可以修改字段为NULL
        if (StringUtils.isEmpty(groupTask.getDocument())) lambdaUpdate.set(GroupTask::getDocument, null);
        //此时生成的SQL语句为update order set price = 3.8, name = null where id = 1
        super.update(groupTask, lambdaUpdate);

        File file = new File(path);
        if (file.exists()){
            file.delete();
        }
        groupTaskMapper.updateById(groupTask);
        return new ResultVO<>(ResponseCode.OK);
    }

    public static void createFile(File file) {
        if (file.exists()) {
            System.out.println("File exists");
        } else {
//            System.out.println("File not exists, create it ...");
            //getParentFile() 获取上级目录(包含文件名时无法直接创建目录的)
            if (!file.getParentFile().exists()) {
//                System.out.println("not exists");
                //创建上级目录
                file.getParentFile().mkdirs();
            }
            try {
                //在上级目录里创建文件
                file.createNewFile();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

}
